<template>
  <div class="login-modal">
    <div class="mask" @click="close"></div>
    <div class="login-box">
      <img @click="close" src="../assets/img/close.png" alt="" />
      <ul>
        <li :class="isShowFrom ? 'active' : ''" @click="isShowFrom = true">
          手机号码登录
        </li>
        <li style="margin: -3px 10px 0; cursor: auto">|</li>
        <li :class="!isShowFrom ? 'active' : ''" @click="weixinClick">
          微信扫码登录
        </li>
      </ul>
      <div class="body">
        <div class="from" v-show="isShowFrom">
          <div class="input-group">
            <input
              ref="phone"
              type="text"
              placeholder="请输入手机号"
              v-model="phoneNum"
            />
          </div>
          <div class="input-group mb20">
            <slide-verify
              :l="42"
              :r="20"
              :w="360"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
            ></slide-verify>
          </div>
          <div class="input-group code mb20">
            <input
              type="text"
              placeholder="请输入短信验证码"
              v-model="SMScode"
            />
            <div class="btn" :class="isShowCount ? 'has-count' : ''">
              <span v-show="!isShowCount" @click="getSMScode">获取验证码</span>
              <span v-show="isShowCount">{{ count }}s</span>
            </div>
          </div>
          <div class="btn" @click="submitLogin">登录</div>
        </div>
        <div class="wx-qrcode" id="weixin" v-show="!isShowFrom">二维码</div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapMutations } from "vuex";
import { validatePhoneNumber } from "@/utils/index.js";
import {
  SendSMSAPI,
  PhoneLoginAPI,
  BindPhoneAPI,
  UserProfilesAPI,
} from "@/request/api.js";
export default {
  data() {
    return {
      //控制表单盒子的显示和隐藏
      isShowFrom: true,
      //图片滑块的验证文字
      msg: "向右滑动",
      //用户输入的手机号
      phoneNum: "17756613836",
      //用户输入的验证码
      SMScode: "1",
      //验证码按钮的倒计时
      isShowCount: false,
      //倒计时数字
      count: 60,
    };
  },
  methods: {
    ...mapMutations({
      chanIsShowLoginModal: "ShowLoginModal/chanIsShowLoginModal",
      chanIsShowed: "isShowLogin/chanIsShowed",
    }),
    ...mapActions({
      asyncChanIsShowToast: "showToast/asyncChanIsShowToast",
      asyncChanUserInfo: "userInfo/asyncChanUserInfo",
    }),
    close() {
      //隐藏登录模态窗口,本质上修改vuex中的isShowLoginModal的值变成false
      this.chanIsShowLoginModal(false);
    },
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "验证成功";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    //点击切换微信二维码
    weixinClick() {
      this.isShowFrom = false;
      // 申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,Lyogd3hsb2dpbi5jc3MgKi8NCi5pbXBvd2VyQm94IC50aXRsZSwgLmltcG93ZXJCb3ggLmluZm97DQogIGRpc3BsYXk6IG5vbmU7DQp9DQoNCg==",
      });
    },
    //验证手机和滑块
    verifyFn() {
      //1.验证用户输入的手机号码格式是否正确,如果不正确就return

      // if (!正则对象.test(用户输入的信息)) {
      if (!validatePhoneNumber(this.phoneNum)) {
        this.asyncChanIsShowToast({
          msg: "请输入正常的手机号!",
          type: "warning",
        });
        //直接给用户聚焦
        this.$refs.phone.focus();
        return false;
      }
      //2.验证滑块拼图,如果不通过就return
      if (this.msg === "向右滑动" || this.msg === "再试一次") {
        //滑块的验证判断
        this.asyncChanIsShowToast({
          msg: "你滑了?Are you kidding me!",
          type: "warning",
        });
        return false; //如果不成功,直接跳出
      }
      return true;
    },
    //点击登录按钮执行的代码
    async submitLogin() {
      //1.手机号码的验证
      //2.图片滑块的验证
      if (!this.verifyFn()) {
        return;
      }
      //3.短信验证码的验证, 如果为空就return
      if (!this.SMScode) {
        this.asyncChanIsShowToast({
          msg: "请输入短信验证码!",
          type: "warning",
        });
        return;
      }
      //登录要根据有没有uuid的情况,发送对应的请求
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        //带uuid的登录
        res = await BindPhoneAPI({
          phone: this.phoneNum.trim(),
          verifyCode: this.SMScode.trim(),
          uuid,
        });
      } else {
        //通过验证,发送登录请求
        res = await PhoneLoginAPI({
          phone: this.phoneNum,
          verifyCode: this.SMScode,
        });
      }

      // console.log(res);
      if (!res) return;
      //登录成功之后的逻辑
      //1.提示用户登录成功
      this.asyncChanIsShowToast({
        msg: "验证成功,正在登录!",
        type: "success",
      });
      //2.关闭登录窗口
      this.close();
      //3.保存token值到localStorage中
      localStorage.setItem("x-auth-token", res["x-auth-token"]);

      //4.登录状态的切换(隐藏登录按钮展示购物车按钮,显示用户昵称头像)
      this.chanIsShowed(true);

      //5.删除uuid   并且清除浏览器地址栏上面的code
      if (uuid) {
        localStorage.removeItem("uuid");
        //清除浏览器地址栏上面的code
        this.$router.push(this.$route.path);
      }

      //登录成功之后,发送用户信息的请求
      // let userInfoRes = await UserProfilesAPI();
      // console.log(userInfoRes);
      this.asyncChanUserInfo();
    },

    //获取短信验证码按钮
    async getSMScode() {
      if (!this.verifyFn()) {
        return;
      }
      //3.发送短信验证码---就是一个请求
      let res = await SendSMSAPI({ phone: this.phoneNum });
      // console.log(res);
      if (res) {
        //获取成功执行这里的代码
        //显示倒计时
        //更改获取验证码变成倒计时
        this.asyncChanIsShowToast({
          msg: "短信验证码已发送!",
          type: "success",
        });
        this.isShowCount = true;

        this.countDown();
      }
    },

    //获取验证码之后的数字倒计时功能
    countDown() {
      let timer = setInterval(() => {
        //每一次count的变化,都需要验证是不是到0了
        //如果到0了,1.关闭定时器  2.隐藏倒计时文字   3.初始化count,变成初始最大值
        this.count--;
        if (this.count === 0) {
          clearInterval(timer);
          this.isShowCount = false;
          this.count = 60;
        }
      }, 1000);
    },
  },
};
</script>
 
<style lang = "less" scoped>
@import url("../assets/css/global.less");
.login-modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .login-box {
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    position: absolute;
    left: 0;
    bottom: 0;
    top: 0;
    right: 0;
    margin: auto;
    img {
      position: absolute;
      right: 60px;
      top: 15px;
      cursor: pointer;
    }
    ul {
      display: flex;
      justify-content: center;
      padding: 40px 0 35px;
      font-size: 18px;
      color: #ccc;
      li {
        cursor: pointer;
      }
      .active {
        color: #000;
      }
    }
    .body {
      width: 360px;
      margin: 0 auto;
      .from {
        .input-group {
          display: flex;

          input {
            height: 48px;
            width: 100%;
            text-indent: 10px;
            border: 1px solid #ccc;
          }
        }
        .code input {
          width: 260px;
          margin-right: 8px;
        }
        .code .btn {
          flex: 1;
        }
        .btn {
          height: 50px;
          line-height: 50px;
          background-color: @base-color;
          color: #fff;
          text-align: center;
        }
        .has-count {
          background-color: #ccc;
        }
      }
    }
  }
}
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
.wx-qrcode {
  display: flex;
  justify-content: center;
  margin-top: -20px;
}
</style>